<!--
 * @Author: wjk
 * @Date: 2020-01-10 10:36:13
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-23 17:56:59
 * @description: 商品套餐
 -->

<template>
  <view>
    <view v-if="goodsPack" class="goods-found">
      <view class="goods-pack-static-box">
        <view v-if="isLive" class="packageGoodsTop" @touchmove.stop>
          <view class="cartClose" @click="closePopup">
            <image src="/static/images/icon/icon_close.png" />
          </view>
          <view class="cartMain">
            <view class="goodsImg">
              <b-image width="180" height="180" :src="goods.pic" />
            </view>
            <view class="priceBox">
              <view class="price">
                <view class="span">套餐价: <view class="b">¥{{ (goods.vip_price) | formatMoney }}</view></view>
              </view>
              <view v-if="packLeast" class="skuDec">节省: ¥{{ packLeast| formatMoney }}</view>
            </view>
          </view>
        </view>
        <scroll-view
          class="package-scroll"
          :style="{'max-height': isLive ? '1000rpx' : 'auto'}"
          scroll-y="true">
          <view :class="isLive? 'package-scroll-box' : ''">
            <view class="goods-found-pack">
              <view class="packLimit">
                套餐搭配商品 <text v-if="goodsPack.pack_selected_num" class="tips">(请选择需要购买的{{ goodsPack.pack_selected_num }}种商品)</text>
              </view>
              <view v-for="(item, index) in orignPackList" :key="index" class="packageIntroIte check-padding">
                <!-- addToPackageList(item, true) -->
                <view v-if="(item.status === 3 || item.status === 0) && (checkSkuNum(item))" class="product-check" @click="addToPackageList(item, false, index, 'package')">
                  <view class="checked-circle" :class="{'checked': packageList.indexOf(item) > -1, 'unable': item.unable}"></view>
                </view>
                <goods-item :need-navigate="false" :show-sub-name="false" :show-tag="false" class-name="goodsPack" from-type="package" :goods-data="item" image-width="140rpx" @click="showPackMask(item, index, 'package')"></goods-item>
                <view v-if="item.checkBorder" class="mask-left" @click="addToPackageList(item, true)"></view>
                <view v-if="item.checkBorder" class="mask-right" @click="showPackMask(item, index, 'package')"></view>
              </view>
            </view>
            <view v-if="orignPresentList.length" class="packageContainer">
              <view class="packLimit color-normal">
                <!-- 赠品规则:  以下赠品可选{{ goodsPack.present_selected_num }}件 -->
                下单即送<text v-if="goodsPack.present_selected_num" class="tips">(以下赠品可选{{ goodsPack.present_selected_num }}件)</text>
              </view>
              <view v-for="(item, index) in orignPresentList" :key="index" class="packageIntroIte check-padding">
                <view v-if="(item.status === 3 || item.status === 0) && (checkSkuNum(item))" class="product-check" @click="addToPresentList(item, false, index, 'present')">
                  <!-- addToPresentList(item, true) -->
                  <view class="checked-circle" :class="{'checked': presentList.indexOf(item) > -1, 'unable': item.unable}"></view>
                </view>
                <goods-item :need-navigate="false" :show-sub-name="false" class-name="goodsPack" from-type="package" :goods-data="item" image-width="140rpx" @click="showPackMask(item, index, 'present')"></goods-item>
                <view v-if="item.checkBorder" class="mask-left" @click="addToPackageList(item, true)"></view>
                <view v-if="item.checkBorder" class="mask-right" @click="showPackMask(item, index, 'present')"></view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <commodity-single ref="package" need-hold :single-goods="singleGoods" mask-type="packSelect" @selectedItem="changeSkuItem($event, singleGoods, singleGoods.selectType)" @closePopup="packClosePopup" @confirm="packConfirm($event, singleGoods, singleGoods.selectType)" />
      <base-popup v-if="!isLive" :show="pShow" :show-close="false" :all-screen="true" :has-scroll="true" @close="closePopup">
        <view class="maskContainer packageMask" :style="'padding-top: '+(statusBarHeight)+'px;height:'+keyboardHeight">
          <view class="packageClose" @click="closePopup">
            <image src="/static/images/icon/icon_return_grey.png" />
            {{ maskType == 'package' ? '套餐购买' : '加入购物车' }}
          </view>
          <view v-if="packageList.length" class="packageContainer popCont">
            <view>
              <view class="packLimit">
                套餐规则: 请选择需要购买的{{ goodsPack.pack_selected_num || 1 }}种商品
              </view>
              <view v-for="(item, index) in packageList" :key="index" class="packageIntroIte">
                <goods-item :need-navigate="false" :show-sub-name="false" :show-tag="false" :goods-data="item" image-width="140rpx"></goods-item>
              </view>
            </view>
            <view v-if="presentList.length">
              <view class="packLimit">
                赠品规则:  以下赠品可选{{ goodsPack.present_selected_num }}件
              </view>
              <view v-for="(item, index) in presentList" :key="index" class="packageIntroIte">
                <goods-item :need-navigate="false" :show-sub-name="false" :goods-data="item" image-width="140rpx"></goods-item>
              </view>
            </view>
          </view>
          <view v-if="goodsPack" class="packBottom">
            <view class="packBuyNum">
              <view class="limit">
                <view class="p">购买数量<view v-if="goodsPack.limit_num != 0" class="span">(限购{{ goodsPack.limit_num }}件)</view></view>
                <view class="packPrice">
                  <!-- 如果是拼团 -->
                  <view v-if="availableGroupBuy">
                    <view>拼团价: <view class="span">¥ {{ (groupInfo.groupPrice) | formatMoney }}</view></view>
                  </view>
                  <view v-else style="display: flex; justify-content: start">
                    <view>套餐价: <view class="span">¥{{ (goods.vip_price) | formatMoney }}</view></view>
                    <view v-if="packLeast !== 0" style="margin-left:5px">节省: <view class="span">¥{{ packLeast | formatMoney }}</view></view>
                  </view>
                </view>
              </view>
              <view class="buyNum">
                <base-stepper :is-adjust="false" :value.sync="buyCountAry.count" :size="42" :min="buyCountAry.min" :max="buyCountAry.max" @inputBlur="blur" @inputFocus="focus" @change="changeQuantity($event)" />
              </view>
            </view>
            <view class="maskBottomBox">
              <view class="maskBottomBtn" @click="cartConfirm">确认</view>
            </view>
          </view>
        </view>
      </base-popup>
    </view>
  </view>
</template>
<script>
import BaseStepper from '@/components/base/base-stepper'
import goodsItem from '@/components/goodsItem/index.vue'
import CommoditySingle from './commodity-single'
export default {
  name: 'CommodityPackage',
  components: {
    BaseStepper,
    CommoditySingle,
    goodsItem
  },
  props: {
    goodsPack: {
      type: Object,
      required: true,
      default: null // 是否显示遮罩层
    },
    groupBuy: {
      type: Object,
      default: () => { return {} } // 拼团数据
    },
    isLive: {
      type: Boolean,
      default: () => { return false } // 是否是直播
    },
    goods: {
      type: Object,
      default: null // 是否显示遮罩层
    },
    buyCountAry: {
      type: Object,
      default: () => {
        return {
          max: 9999,
          min: 1,
          count: 1
        }
      }
    }
  },
  data() {
    return {
      selectedSkuItem: null,
      pShow: false,
      availableGroupBuy: false,
      maskType: '',
      buyType: '',
      singleGoods: {},
      groupInfo: {},
      orignPackList: [],
      statusBarHeight: 0,
      orignPresentList: [],
      packageList: [],
      presentList: [],
      buyCountAryOrigin: null,
      keyboardHeight: '100%'
    }
  },
  computed: {
    packLeast() {
      // 套餐节省金额
      if (this.goods.type === 1) {
        return 0
      } else {
        let count = 0
        if (this.goods.goods_pack.pack_selected_num > this.packageList.length) {
          return count
        }
        let enableNext = true
        this.packageList.forEach(element => {
          if (!element.selectedSkuItem) {
            enableNext = false
          }
        })
        if (!enableNext) {
          return count
        }
        count = this.goods.vip_price
        this.packageList.forEach(item => {
          if (item.selectedSkuItem) {
            count=this.$utils.math.cut(count,this.$utils.math.mul(item.selectedSkuItem.vip_price,item.selectedSkuItem.package_goods_number));//使用utils.js中math方法计算，防止精度丢失
          }
        })
        if (this.presentList.length) {
          this.presentList.forEach(item => {
            if (item.selectedSkuItem) {
              count=this.$utils.math.cut(count,this.$utils.math.mul(item.selectedSkuItem.vip_price,item.selectedSkuItem.package_goods_number));//使用utils.js中math方法计算，防止精度丢失
            }
          })
        }
        this.$emit('packLeast', Math.abs(count * this.buyCountAry.count))
        return Math.abs(count)
      }
    }
  },
  created() {
    uni.getSystemInfo({
      success: ({ statusBarHeight }) => {
        this.statusBarHeight = statusBarHeight
      }
    })
    if (this.goods.type === 2) { // 如果是套餐 pack_type 1固定套餐2自由组合套餐
      /* 如果套餐个数和必须选择的数量相等 */
      // this.orignPackList =
      const selectAll = this.goods.goods_pack.pack.length === this.goods.goods_pack.pack_selected_num
      this.orignPackList = this.goodsPack.pack.map((item, index) => {
        item.selfId = item.goods_id + index
        // item.properties_name = '请选择'
        if (item.sku_list && item.sku_list.length === 1) {
          try {
            item.sku_list[0].selectText = item.sku_list[0].properties_name.split(';').reduce((a, b) => a.split(':')[1] + '; ' + b.split(':')[1])
          } catch (e) {
            console.log('e', e)
          }
          this.changeSkuItem(item.sku_list[0], item, 'package')
        } else {
          this.changeSkuItem(null, item, 'package')
        }
        if ((selectAll || this.goods.pack_type === 1) && Number(item.status === 3)) {
          item.unable = true
          this.packageList.push(item)
        }
        return item
      })
      // console.log(this.orignPackList)
      // this.collectSuitSensor('suitDetail')
    }
    /** 赠品全选逻辑 */
    if (this.goods.goods_pack && this.goods.goods_pack.present.length) {
      const presentAll = this.goods.goods_pack.present.length === this.goods.goods_pack.present_selected_num
      this.orignPresentList = this.goods.goods_pack.present.map((item, index) => {
        item.selfId = item.goods_id + index
        // item.properties_name = '请选择'
        if (item.sku_list && item.sku_list.length === 1) {
          try {
            item.sku_list[0].selectText = item.sku_list[0].properties_name.split(';').reduce((a, b) => a.split(':')[1] + '; ' + b.split(':')[1])
          } catch (e) {
            console.log('e', e)
          }
          this.changeSkuItem(item.sku_list[0], item, 'present')
        } else {
          this.changeSkuItem(null, item, 'present')
        }
        if (presentAll) {
          item.unable = true
          this.presentList.push(item)
        }
        return item
      })
    }
  },
  methods: {
    // 拼团设置最大值
    setMax() {
      if (!this.buyCountAryOrigin) {
        const origin = JSON.stringify(this.buyCountAry)
        this.buyCountAryOrigin = JSON.parse(origin)
      }
      console.log('setMax')
      this.$set(this.buyCountAry, 'max', this.groupBuy.groupInfo.groupLimit)
      if (this.buyCountAry.count > this.groupBuy.groupInfo.groupLimit) {
        this.$set(this.buyCountAry, 'count', this.groupBuy.groupInfo.groupLimit)
        this.$emit('buyCountChangeMax', this.buyCountAry.max)
      }
    },
    // 最大值还原
    resetMax() {
      if (!this.buyCountAryOrigin) {
        const origin = JSON.stringify(this.buyCountAry)
        this.buyCountAryOrigin = JSON.parse(origin)
      }
      let result
      if (this.selectedSkuItem) {
        result = (this.selectedSkuItem && this.selectedSkuItem.order_limit) !== 0 ? this.selectedSkuItem.order_limit : this.buyCountAryOrigin.max
      } else {
        result = this.buyCountAryOrigin.max
      }
      this.$set(this.buyCountAry, 'max', result)
      this.$emit('buyCountChangeMax', result)
    },
    checkSkuNum() {
      return true
    },
    showPopup(limit) {
      if (!this.checkSkuEnable()) {
        return
      }
      if (this.groupBuy.availableGroupBuy) {
        this.availableGroupBuy = (limit === 'openGroup' ? this.groupBuy.availableGroupBuy : false)
        this.groupInfo = this.groupBuy.groupInfo
      }
      this.buyType = limit
      this.maskType = limit === 'buyBtn' ? 'package' : 'packageCart'
      if (limit === 'groupSingleBuy' || limit === 'openGroup') {
        this.maskType = 'package'
      }
      if (this.isLive) {
        this.cartConfirm()
        return
      }
      this.pShow = true
    },
    closePopup() {
      this.pShow = false
      this.$emit('close')
    },
    changeQuantity(num) {
      this.$emit('buyCountChange', num)
      this.$emit('buyCountChangeMax', this.buyCountAry.max)
      // this.$set(this.buyCountAry, 'count', num)
    },
    showPackMask(item, index, type) {
      this.singleGoods = item
      this.singleGoods.selectType = type
      this.orignPackList.map(item => {
        item.checkBorder = false
        return item
      })
      if (!item.sku_list || item.sku_list.length === 1) {
        return
      }
      this.$refs['package'].showPopup()
      if (this.isLive) {
        this.$emit('hideNumDialog', true)
      }
    },
    packClosePopup() {
      if (this.isLive) {
        this.$emit('hideNumDialog', false)
      }
    },
    checkSkuEnable() {
      if (this.goods.goods_pack && this.goods.goods_pack.pack && this.goods.goods_pack.pack.length) {
        let limit = false
        const selectNum = this.goods.goods_pack.pack_selected_num
        if (this.packageList.length < selectNum) {
          limit = true
        }
        this.packageList.forEach(element => {
          if (!element.selectedSkuItem) {
            limit = true
            // const index = this.orignPackList.findIndex(item => item.goods_id === element.goods_id)
            const index = this.orignPackList.findIndex(item => item.selfId === element.selfId)
            if (index > -1) {
              this.orignPackList[index].checkBorder = true
            }
          }
        })

        if (limit) {
          const hasSelectNum = this.packageList.filter(item => !!item.selectedSkuItem).length
          const title = `该套餐需要选择${selectNum}种商品 已选择${hasSelectNum}种商品规格，请在选择${selectNum - hasSelectNum}种商品规格~`
          uni.showToast({
            title: title,
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
      }

      if (this.goods.goods_pack && this.goods.goods_pack.present && this.goods.goods_pack.present.length) {
        if (this.presentList.length < this.goods.goods_pack.present_selected_num) {
          uni.showToast({
            title: '请按规则选择赠品',
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
        let limit = false
        this.presentList.forEach(element => {
          if (!element.selectedSkuItem) {
            limit = true
            // const index = this.orignPresentList.findIndex(item => item.goods_id === element.goods_id)
            const index = this.orignPresentList.findIndex(item => item.selfId === element.selfId)
            if (index > -1) {
              this.orignPresentList[index].checkBorder = true
            }
          }
        })
        if (limit) {
          const selectNum = this.goods.goods_pack.present_selected_num
          const hasSelectNum = this.presentList.filter(item => !!item.selectedSkuItem).length
          const title = `该套餐需要选择${selectNum}种赠品 已选择${hasSelectNum}种赠品规格，请再选择${selectNum - hasSelectNum}种赠品规格~`
          uni.showToast({
            title: title,
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
      }
      return true
    },
    cartConfirm() {
      this.$emit('confirm', {
        selectedSkuItem: this.selectedSkuItem,
        count: this.buyCountAry.count,
        maskType: this.maskType,
        packageList: this.packageList,
        presentList: this.presentList,
        buyType: this.buyType
      })
      this.closePopup()
    },
    addToPackageList(item, need, i, type) {
      if (this.goodsPack.pack_type === 1 && !need || Number(item.status) !== 3) {
        return
      }
      if (!item.selectedSkuItem) {
        this.showPackMask(item, i, type)
        return
      }
      let index = -1
      this.packageList.forEach((element, i) => {
        // if (item.goods_id === element.goods_id) {
        if (item.selfId === element.selfId) {
          index = i
        }
      })
      if (index > -1 && !need) {
        this.packageList.splice(index, 1)
        return
      }
      if (this.goodsPack.pack_type === 0 && !item.selectedSkuItem) {
        return
      }
      if (index > -1) {
        this.packageList.splice(index, 1)
      }
      this.packageList.push(item)
      if (this.goodsPack.pack_selected_num < this.packageList.length && this.packageList.length > 1) {
        this.packageList.shift()
      }
    },
    addToPresentList(item, need, i, type) {
      if (!item.selectedSkuItem) {
        this.showPackMask(item, i, type)
        return
      }
      const index = this.presentList.indexOf(item)
      if (index > -1 && !need) {
        this.presentList.splice(index, 1)
        return
      }
      if (index > -1) {
        this.presentList.splice(index, 1)
      }
      this.presentList.push(item)

      if (this.goodsPack.present_selected_num < this.presentList.length) {
        this.presentList.shift()
      }
    },
    packConfirm(obj, ringe, type) {
      if (type === 'present' || type === 'presentSelect') {
        this.addToPresentList(ringe, true)
      } else if (type === 'package' || type === 'packSelect') {
        this.addToPackageList(ringe, true)
      }
    },
    changeSkuItem(item, ringe, type) {
      this.$set(this, 'selectedSkuItem', item)
      if (ringe) {
        this.$set(ringe, 'selectedSkuItem', item)
        // this.$forceUpdate()
        if (item) {
          this.$set(ringe, 'properties_name', item.selectText)
          this.$set(ringe, 'num', item.package_goods_number)
        } else {
          this.$set(ringe, 'properties_name', '请选择')
          this.$set(ringe, 'num', ringe.sku_list[0] ? ringe.sku_list[0].package_goods_number : '0')
        }
        this.$set(ringe, 'checkBorder', false)
      }
    },
    focus(e) {
      // 获取键盘的高度 h5是没有的
      // #ifdef MP-WEIXIN
      console.log(e)
      // console.log(e.target.height)
      const res = uni.getSystemInfoSync()

      this.keyboardHeight = `${res.windowHeight - e.target.height}px`
      // #endif
    },
    blur(e) {
      this.keyboardHeight = '100%'
    }
  }
}
</script>
<style lang="scss" scoped>
.packageMask{
  height: 100%;
  border-radius: 0;
  padding: 0;
  box-sizing: border-box;
  .packageClose{
    position: relative;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 18px;
    border-bottom: 1px solid #efefef;
    image{
      position: absolute;
      width: 20px;
      height: 20px;
      top: 10px;
      left: 10px;
    }
  }
  .packBottom{
    .packBuyNum{
      padding: 10px;
      padding-right:40rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .limit{
        .p{font-weight: bold; font-size: 16px; .span{color: $color-tips; margin-left: 10px;font-size: 14px;}}
        .packPrice{margin-top: 5rpx; .span{color: $color-price;margin-left: 5px; display: inline-block;} display: flex;}
      }
    }
    .maskBottomBox{
      // box-shadow: 0px -3px 5px #efefef;
      padding: 10px;
    }
    .maskBottomBtn{
      width: auto;
      margin: 0;
      margin-top: 20rpx;
    }
  }
}
.popCont{
  overflow: auto;
  height: calc(100% - 200px);
  padding: 0 16rpx;
}
.tips{
  padding-left: 10rpx;
  font-weight: normal;
  color: #FF7F00;
}
.goods-pack-static-box{
  .package-scroll{
    .package-scroll-box{
      padding: 0rpx 20rpx 200rpx 20rpx ;
    }
  }
  .packageGoodsTop{
    position: relative;
    background-color: #fff;
    left: 0;
    width: 100%;
    .cartClose{
      top: 10rpx;
    }
    .cartMain {
      padding: 0 20rpx;
      vertical-align: middle;
      display: flex;
      justify-content: left;
      .goodsImg {
        display: inline-block;
        margin: -60rpx 30rpx 0rpx 0px;
        image {width: 180rpx; height: 180rpx; border-radius: 5px; border: 1px solid #eaeaea;}
      }
      .priceBox {
        .price {
          .span {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;
            .b{
              font-weight: bold;
              display: inline-block;
              font-size: 28rpx;
            }
            color: $color-price;
            font-size: 28rpx;
          }
        }
        .skuDec {color: $color-tips; font-size: 12px;}
      }
    }
  }
}

.packageContainer{
  .packLimit{
    color: $color-theme;
    line-height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }
  .color-normal{
    color: $color-normal;
    border-bottom: none;
    line-height: 60rpx;
  }
}
  .goods-found {
   .packLimit {
     padding: 10rpx 0;
   }
   .packageIntroIte {
     padding-right:10rpx;
    .product-check {
      left: 8rpx;
      top: 50%;
      margin-top: -20rpx;
    }
  }
  .mask-left,.mask-right {
    background-color: #000;

    position: absolute;
    top: 0;
    bottom: 0;
    opacity: 0.3;
  }
  .mask-left {
    width: 30rpx;
    left: 0;
    border-top-left-radius: 20rpx;
    border-bottom-left-radius: 20rpx;
  }
  .mask-right {
    width: calc(100% - 30rpx);
    right: 0;
    border-top-right-radius: 20rpx;
    border-bottom-right-radius: 20rpx;
  }
  .packageIntroIte{
    border-bottom: 1px solid #efefef;
    padding: 20rpx 0 20rpx 0rpx;
    &.check-padding{
      padding-left: 60rpx;
    }
    position: relative;
    .product-check{
      width: 20px;
      height: 20px;
      position: absolute;
      left: 0px;
      top: 40px;
      .checked-circle{
        display: block;
        width: 20px;
        height: 20px;
        background: url('~@/static/images/icon/icon_marquee.png') no-repeat;
        background-size: 100% 100%;
      }
      .checked{
        background: url('~@/static/images/icon/icon_radio_active.png') no-repeat;
        background-size: 100% 100%;
      }
      .unable{
        background: url('~@/static/images/icon/icon_marquee_unable.png') no-repeat;
        background-size: 100% 100%;
      }
    }
  }
 }

</style>
